package com.atguigu.lease.web.admin.custom.interceptor;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

//身份验证拦截器
@Component//将JWT，放置于HTTP请求的Header中，其Header的key为`access_token`。
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //todo 前端规定在请求头中所携带的token的键是access_token
        // 获取请求头中所携带的token
        String token = request.getHeader("access_token");
        // 判断是否携带token
//        if (token == null) {
        if (!StringUtils.hasText(token)) {
            //表示当前请求没有携带token，抛出未登录异常
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        } else {
            //表示当前请求携带有Token
            //通过Jwt工具类解析Token,获取其中信息
            Claims claims = JwtUtil.parseToken(token);
            //获取userID
            Long userId = claims.get("userId", Long.class);
            //获取username
            String username = claims.get("username", String.class);
            //将获取到的信息鵆到TreadLocal
            LoginUserContext.setLoginUser(new LoginUser(userId, username));
        }
        return true;
    }

    //线程结束后清理TreadLocal中的数据,避免影响下一次线程登录
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserContext.clear();
    }
}